﻿using System;
using System.BLL;
using System.Collections.Generic;
using System.Dto;
using System.IBLL;
using System.IO;
using System.Linq;
using System.MVC.Models;
using System.Net;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace System.MVC.Controllers
{
    public class HouseholdController : Controller
    {
        /// <summary>
        /// 住户管理页面的控制器
        /// </summary>
        /// <returns></returns>
        public ActionResult HouseholdList()
        {
            return View();
        }
        /// <summary>
        /// 住户管理table表数据获取接口
        /// </summary>
        /// <param name="limit">条数</param>
        /// <param name="page">页数</param>
        /// <param name="UserName">用户名筛选</param>
        /// <param name="PhoneNumber">电话筛选</param>
        /// <param name="sex">性别筛选</param>
        /// <returns></returns>
        public JsonResult GetHouseHoldList(int limit, int page, string UserName, string PhoneNumber, string sex)
        {
            IHouseholdManager manager = new HouseholdManager();
            int datalet;
            var data = manager.GetHouseholdLists(limit, page, UserName, PhoneNumber, sex, out datalet);
            return Json(new { code = 0, msg = "获取成功", count=datalet, data=data }, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 住户添加的页面控制器
        /// </summary>
        /// <returns></returns>
        public ActionResult AddHousehold()
        {
            return View();
        }
        /// <summary>
        /// 住户添加页面的tableSelect下拉框数据请求接口
        /// </summary>
        /// <param name="limit">条数</param>
        /// <param name="page">页数</param>
        /// <param name="StoreyName">房间号筛选器</param>
        /// <returns></returns>
        public JsonResult GettableSelectStorey(int limit,int page,string StoreyName)
        {
            IHouseholdManager manager = new HouseholdManager();
            int datalet;
            var data = manager.GettableSelectStoreyList(limit, page, StoreyName, out datalet);

            return Json(new { code = 0, msg = "获取成功", count = datalet, data = data }, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 住户添加页面数据添加请求接口
        /// </summary>
        /// <param name="models">数据模型</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AddHousehold(AddHouseholdViewModels models)
        {
            IHouseholdManager manager = new HouseholdManager();
            manager.AddNewOneHouseholdAsync(models.UserName, models.PassWord, models.Sex);
            Thread.Sleep(1000);
            int id = manager.GetOneHouseholdIdByUserName(models.UserName);
            manager.AddHouseholdToStorey(id, models.StoreyId, models.IsOwner);
            return Json(new { code = 0, msg = "获取成功"});
        }
        /// <summary>
        /// 住户管理界面table表删除按钮数据请求接口
        /// </summary>
        /// <param name="id">住户ID</param>
        /// <returns></returns>
        public JsonResult DelHousehold(int id)
        {
            IHouseholdManager manager = new HouseholdManager();
            manager.DelHouseholdById(id);
            manager.DelHouseholdToStoreyById(id);
            return Json(new { code = 0, msg = "删除成功"}, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 住户修改页面控制器
        /// </summary>
        /// <param name="id">住户ID</param>
        /// <returns></returns>
        public ActionResult EditHousehold(int id)
        {
            IHouseholdManager manager = new HouseholdManager();
            var data = manager.GetOneHouseholdById(id);
            return View(data);
        }
        /// <summary>
        /// 住户修改页面修改按钮数据请求接口
        /// </summary>
        /// <param name="list">数据模型</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult EditHousehold(HouseHoldList list)
        {
            IHouseholdManager manager = new HouseholdManager();
            manager.EditOneHouseholdByDto(list);
            manager.EditOneHouseholdToStorey(list.Id, list.IsOwner);
            return Json(new { code = 0, msg = "修改成功" });
        }
        /// <summary>
        /// 临时进出管理页面
        /// </summary>
        /// <returns></returns>
        public ActionResult TemporaryAccessList() 
        {
            return View();
        }
        /// <summary>
        /// 临时进出管理页面table数据获取接口
        /// </summary>
        /// <param name="limit">条数</param>
        /// <param name="page">页数</param>
        /// <param name="ApplicationName">申请人筛选</param>
        /// <returns></returns>
        public JsonResult GetTemporaryAccessList(int limit, int page, string ApplicationName)
        {
            IHouseholdManager manager = new HouseholdManager();
            int datalet;
            var data = manager.GetTemporaryAccessLists(limit, page, ApplicationName, out datalet);
            return Json(new { code = 0, msg = "获取成功", count = datalet, data = data }, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 临时进出管理页面table审核按钮数据请求接口
        /// </summary>
        /// <param name="id">申请ID</param>
        /// <param name="examineResult">审核结果</param>
        /// <returns></returns>
        public JsonResult ExamineTemporaryAccess(int id,string examineResult)
        {
            /*IHouseholdManager manager = new HouseholdManager();
            manager.ExamineOneTemporaryAccessById(id, examineResult, Session["UserName"].ToString());*/
            return Json(new { code = 0, msg = "审核完成" }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult postTemporary()
        {
            IHouseholdManager manager = new HouseholdManager();
            var url = manager.GetNewOneTemporaryAccessByName(Session["UserName"].ToString());
            ViewBag.url = url;
            return View();
        }

        [HttpPost]
        public JsonResult postTemporary(TemporaryModel model)
        {
            IHouseholdManager manager = new HouseholdManager();
            string guid = Guid.NewGuid().ToString();

            WebRequest request = WebRequest.Create("https://api.pwmqr.com/qrcode/create/?url="+guid);
            request.Method = "Get";
            WebResponse response = request.GetResponse();
            Stream reader = response.GetResponseStream();
            string url = @"/img/" + guid+".png";
            string path = Server.MapPath(url);
            FileStream writer = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
            byte[] buff = new byte[512];
            int c = 0; //实际读取的字节数
            while ((c = reader.Read(buff, 0, buff.Length)) > 0)
            {
                writer.Write(buff, 0, c);
            }
            writer.Close();
            writer.Dispose();
            reader.Close();
            reader.Dispose();
            response.Close();

            manager.ExamineOneTemporaryAccessById(Session["UserName"].ToString(), model.accessReason, url, model.remark, guid);

            return Json(new { code = 0, msg = "申请成功", url = url });
        }

        public string TemporaryToUse(string id)
        {
            IHouseholdManager manager = new HouseholdManager();
            var data = manager.getOneAccessByPass(id);
            if (data == null)
            {
                return "该二维码异常";
            }
            string nowTime = DateTime.Now.ToString("yyyy-MM-dd");
            data.ApplicationTime = DateTime.Parse(data.ApplicationTime).ToString("yyyy-MM-dd");
            if (data.ApplicationTime != nowTime)
                return "该二维码已失效";
            bool isout = false;
            if (data.OutTime == "已出去")
            {
                return "该二维码已使用！";
            }
            if (data.EnterTime == "已进入")
                isout = true;
            manager.CheangTimeByPass(id,isout);
            if(isout)
                return "出社区成功";
            return "进社区成功";
        }

        public ActionResult BatchInputByExcel()
        {
            return View();
        }
        [HttpPost]
        public JsonResult upload()
        {
            IBatchInputByExcelManager manager = new BatchInputByExcelManager();
            var uploadedFile = Request.Files[0];
            string fileName = Path.GetFileName(uploadedFile.FileName.ToString());
            string fileNameEx = Path.GetExtension(fileName);
            var buf = new byte[uploadedFile.InputStream.Length];
            uploadedFile.InputStream.Read(buf, 0, (int)uploadedFile.InputStream.Length);
            Stream data = new MemoryStream(buf);

            manager.UserBatchInput(data, fileNameEx);
            return Json(new { code = 0, msg = "成功" });
        }


        public ActionResult GetMyRegistrationActivity()
        {
            return View();
        }

        public JsonResult GetMyActivity(int limit, int page, string activityName)
        {
            IHouseholdManager manager = new HouseholdManager();
            int datalet;
            int userId = int.Parse(Session["userid"].ToString());
            var data = manager.GetMyActivityLists(userId, limit, page, activityName, out datalet);
            return Json(new { code = 0, msg = "获取成功", count = datalet, data = data }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult EditMyActivityRegistration(int id)
        {
            IHouseholdManager manager = new HouseholdManager();
            var data = manager.GetOneActivityById(id);
            ViewBag.partakeCount = data.PartakeCount;
            ViewBag.phone = data.phone;
            ViewBag.remark = data.remark;
            ViewBag.id = data.Id;
            return View();
        }

        [HttpPost]
        public JsonResult EditMyActivityRegistration(ActivityRegistrationDto dto)
        {
            IHouseholdManager manager = new HouseholdManager();
            manager.EditOneAcivityByDto(dto);
            return Json(new { code = 0, msg = "修改成功" });
        }

        public ActionResult MyMessageList()
        {
            //GetMessageListDto
            return View();
        }

        public JsonResult GetMyMessage(int limit, int page, string messageText)
        {
            IHouseholdManager manager = new HouseholdManager();
            int datalet;
            int userId = int.Parse(Session["userid"].ToString());
            var data = manager.getMyMessageListByDtos(userId, limit, page, messageText, out datalet);
            return Json(new { code = 0, msg = "获取成功", count = datalet, data = data }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult DelMyMessage(int id)
        {
            IHouseholdManager manager = new HouseholdManager();
            manager.DelMyOneMessageById(id);
            return Json(new { code = 0, msg = "删除成功" });
        }


        public ActionResult MyGuaranteeList()
        {
            return View();
        }

        public JsonResult GetMyUserGuaranteeList(int limit, int page, string RepairTitle, string RepairContent)
        {
            IRepairManager manager = new RepairManager();
            int datalet;
            string userName = Session["UserName"].ToString();
            var data = manager.GetMyUserGuaranteeLists(userName,limit, page, out datalet, RepairTitle, RepairContent);
            return Json(new { code = 0, msg = "获取成功", count = datalet, data = data }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult WriteEvaluate(int id)
        {
            ViewBag.id = id;
            return View();
        }

        [HttpPost]
        public JsonResult WriteEvaluate(GetUserGuaranteeListDto dto)
        {
            IRepairManager manager = new RepairManager();
            manager.WriteEvaluateById(dto.Id, dto.Evaluate);
            return Json(new { code = 0, msg = "留言成功" });
        }

        public ActionResult EditInfo()
        {
            int id = int.Parse(Session["userid"].ToString());
            IHouseholdManager manager = new HouseholdManager();
            var data =  manager.GetOneHouseholdById(id);
            
            return View(data);
        }

        public JsonResult EditMyHousehold(HouseHoldList list)
        {
            IHouseholdManager manager = new HouseholdManager();
            manager.EditOneHouseholdByDto(list);
            return Json(new { code = 0, msg = "修改成功" });
        }

    }
}